const initData = {
    list: JSON.parse(localStorage.getItem('list')) || []
}

const homeReducer = (state = initData, { type, payload }) => {

    switch (type) {

        case 'GET_LIST':
            return {
                ...state,
                list: payload
            }

        case 'DETELE':

            state.list.splice(payload, 1)

            localStorage.setItem('list', JSON.stringify(state.list))

            return {
                ...state,
                list: [...state.list]
            }

        case 'SAVE_BTN':

            state.list.forEach((item) => {
                if (item.id === payload.Id) {
                    item.name = payload.Name
                    item.city = payload.City
                    item.title = payload.Title
                }
            })

            localStorage.setItem('list', JSON.stringify(state.list))

            return {
                ...state,
                list: [...state.list]
            }

        case 'ADD_BTN':

            state.list.push(payload)

            localStorage.setItem('list', JSON.stringify(state.list))

            return {
                ...state,
                list: [...state.list]
            }

        case 'CORRECT':

            state.list.sort((a, b) => {
                return a.name - b.name
            })

            localStorage.setItem('list', JSON.stringify(state.list))

            return {
                ...state,
                list: [...state.list]
            }

        case 'POUR':

            state.list.sort((a, b) => {
                return b.name - a.name
            })

            localStorage.setItem('list', JSON.stringify(state.list))

            return {
                ...state,
                list: [...state.list]
            }

        default:
            return {
                ...state
            }
    }

}

export default homeReducer